package com.huawei.hms.support.api;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Pair;
import com.huawei.hms.core.aidl.AbstractMessageEntity;
import com.huawei.hms.core.aidl.IMessageEntity;
import com.huawei.hms.support.api.client.ApiClient;
import com.huawei.hms.support.api.client.InnerPendingResult;
import com.huawei.hms.support.api.client.Result;
import com.huawei.hms.support.api.client.ResultCallback;
import com.huawei.hms.support.api.client.Status;
import com.huawei.hms.support.api.entity.core.CommonCode.ErrorCode;
import com.huawei.hms.support.api.transport.DatagramTransport;
import com.huawei.hms.support.log.HMSLog;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class PendingResultImpl<R extends Result, T extends IMessageEntity> extends InnerPendingResult<R> {
    private CountDownLatch a;
    private R b = null;
    private WeakReference<ApiClient> c;
    protected DatagramTransport transport = null;

    protected static class a<R extends Result> extends Handler {
        public a() {
            this(Looper.getMainLooper());
        }

        public void a(ResultCallback<? super R> resultCallback, R r) {
            sendMessage(obtainMessage(1, new Pair(resultCallback, r)));
        }

        public void handleMessage(Message message) {
            switch (message.what) {
                case 1:
                    Pair pair = (Pair) message.obj;
                    b((ResultCallback) pair.first, (Result) pair.second);
                    return;
                default:
                    return;
            }
        }

        public a(Looper looper) {
            super(looper);
        }

        protected void b(ResultCallback<? super R> resultCallback, R r) {
            resultCallback.onResult(r);
        }
    }

    public abstract R onComplete(T t);

    public PendingResultImpl(ApiClient apiClient, String str, IMessageEntity iMessageEntity) {
        a(apiClient, str, iMessageEntity, getResponseType());
    }

    public PendingResultImpl(ApiClient apiClient, String str, IMessageEntity iMessageEntity, Class<T> cls) {
        a(apiClient, str, iMessageEntity, cls);
    }

    private void a(ApiClient apiClient, String str, IMessageEntity iMessageEntity, Class<T> cls) {
        Throwable e;
        HMSLog.i("PendingResultImpl", "init uri:" + str);
        if (apiClient == null) {
            HMSLog.e("PendingResultImpl", "client is null");
            return;
        }
        this.c = new WeakReference(apiClient);
        this.a = new CountDownLatch(1);
        try {
            this.transport = (DatagramTransport) Class.forName(apiClient.getTransportName()).getConstructor(new Class[]{String.class, IMessageEntity.class, Class.class}).newInstance(new Object[]{str, iMessageEntity, cls});
        } catch (InstantiationException e2) {
            e = e2;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        } catch (IllegalAccessException e3) {
            e = e3;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        } catch (IllegalArgumentException e4) {
            e = e4;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        } catch (InvocationTargetException e5) {
            e = e5;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        } catch (NoSuchMethodException e6) {
            e = e6;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        } catch (ClassNotFoundException e7) {
            e = e7;
            HMSLog.e("PendingResultImpl", "gen transport error:" + e.getMessage());
            throw new IllegalStateException("Instancing transport exception, " + e.getMessage(), e);
        }
    }

    protected Class<T> getResponseType() {
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass != null) {
            genericSuperclass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[1];
            if (genericSuperclass != null) {
                return (Class) genericSuperclass;
            }
        }
        return null;
    }

    public final R await() {
        HMSLog.i("PendingResultImpl", "await");
        if (Looper.myLooper() != Looper.getMainLooper()) {
            return awaitOnAnyThread();
        }
        HMSLog.e("PendingResultImpl", "await in main thread");
        throw new IllegalStateException("await must not be called on the UI thread");
    }

    public final R awaitOnAnyThread() {
        HMSLog.i("PendingResultImpl", "awaitOnAnyThread");
        if (this.c == null) {
            HMSLog.e("PendingResultImpl", "api is null");
            a(ErrorCode.CLIENT_API_INVALID, null);
            return this.b;
        }
        ApiClient apiClient = (ApiClient) this.c.get();
        if (checkApiClient(apiClient)) {
            this.transport.send(apiClient, new 1(this));
            try {
                this.a.await();
            } catch (InterruptedException e) {
                HMSLog.e("PendingResultImpl", "await in anythread InterruptedException");
                a(ErrorCode.INTERNAL_ERROR, null);
            }
            return this.b;
        }
        HMSLog.e("PendingResultImpl", "client invalid");
        a(ErrorCode.CLIENT_API_INVALID, null);
        return this.b;
    }

    public R await(long j, TimeUnit timeUnit) {
        HMSLog.i("PendingResultImpl", "await timeout:" + j + " unit:" + timeUnit.toString());
        if (Looper.myLooper() != Looper.getMainLooper()) {
            return awaitOnAnyThread(j, timeUnit);
        }
        HMSLog.i("PendingResultImpl", "await in main thread");
        throw new IllegalStateException("await must not be called on the UI thread");
    }

    public final R awaitOnAnyThread(long j, TimeUnit timeUnit) {
        HMSLog.i("PendingResultImpl", "awaitOnAnyThread timeout:" + j + " unit:" + timeUnit.toString());
        if (this.c == null) {
            HMSLog.e("PendingResultImpl", "api is null");
            a(ErrorCode.CLIENT_API_INVALID, null);
            return this.b;
        }
        ApiClient apiClient = (ApiClient) this.c.get();
        if (checkApiClient(apiClient)) {
            final AtomicBoolean atomicBoolean = new AtomicBoolean();
            this.transport.post(apiClient, new com.huawei.hms.support.api.transport.DatagramTransport.a(this) {
                final /* synthetic */ PendingResultImpl b;

                public void a(int i, IMessageEntity iMessageEntity) {
                    if (!atomicBoolean.get()) {
                        this.b.a(i, iMessageEntity);
                    }
                    this.b.a.countDown();
                }
            });
            try {
                if (!this.a.await(j, timeUnit)) {
                    atomicBoolean.set(true);
                    a(ErrorCode.EXECUTE_TIMEOUT, null);
                }
            } catch (InterruptedException e) {
                HMSLog.e("PendingResultImpl", "awaitOnAnyThread InterruptedException");
                a(ErrorCode.INTERNAL_ERROR, null);
            }
            return this.b;
        }
        HMSLog.e("PendingResultImpl", "client invalid");
        a(ErrorCode.CLIENT_API_INVALID, null);
        return this.b;
    }

    public void setResultCallback(ResultCallback<R> resultCallback) {
        setResultCallback(Looper.getMainLooper(), resultCallback);
    }

    public final void setResultCallback(Looper looper, final ResultCallback<R> resultCallback) {
        HMSLog.i("PendingResultImpl", "setResultCallback");
        if (looper == null) {
            looper = Looper.myLooper();
        }
        final a aVar = new a(looper);
        if (this.c == null) {
            HMSLog.e("PendingResultImpl", "api is null");
            a(ErrorCode.CLIENT_API_INVALID, null);
            return;
        }
        ApiClient apiClient = (ApiClient) this.c.get();
        if (checkApiClient(apiClient)) {
            this.transport.post(apiClient, new com.huawei.hms.support.api.transport.DatagramTransport.a(this) {
                final /* synthetic */ PendingResultImpl c;

                public void a(int i, IMessageEntity iMessageEntity) {
                    this.c.a(i, iMessageEntity);
                    aVar.a(resultCallback, this.c.b);
                }
            });
            return;
        }
        HMSLog.e("PendingResultImpl", "client is invalid");
        a(ErrorCode.CLIENT_API_INVALID, null);
        aVar.a(resultCallback, this.b);
    }

    @Deprecated
    public void cancel() {
    }

    @Deprecated
    public boolean isCanceled() {
        return false;
    }

    @Deprecated
    public void setResultCallback(ResultCallback<R> resultCallback, long j, TimeUnit timeUnit) {
        setResultCallback(resultCallback);
    }

    private void a(int i, IMessageEntity iMessageEntity) {
        HMSLog.i("PendingResultImpl", "setResult:" + i);
        Status status = null;
        if (iMessageEntity != null && (iMessageEntity instanceof AbstractMessageEntity)) {
            status = ((AbstractMessageEntity) iMessageEntity).getCommonStatus();
        }
        if (i == 0) {
            this.b = onComplete(iMessageEntity);
        } else {
            this.b = onError(i);
        }
        if (this.b != null) {
            Status status2 = this.b.getStatus();
            if (status2 != null && status != null) {
                int statusCode = status2.getStatusCode();
                Object statusMessage = status2.getStatusMessage();
                int statusCode2 = status.getStatusCode();
                String statusMessage2 = status.getStatusMessage();
                if (statusCode != statusCode2) {
                    HMSLog.e("PendingResultImpl", "rstStatus code (" + statusCode + ") is not equal commonStatus code (" + statusCode2 + ")");
                    HMSLog.e("PendingResultImpl", "rstStatus msg (" + statusMessage + ") is not equal commonStatus msg (" + statusMessage2 + ")");
                } else if (TextUtils.isEmpty(statusMessage) && !TextUtils.isEmpty(statusMessage2)) {
                    HMSLog.i("PendingResultImpl", "rstStatus msg (" + statusMessage + ") is not equal commonStatus msg (" + statusMessage2 + ")");
                    this.b.setStatus(new Status(statusCode, statusMessage2, status2.getResolution()));
                }
            }
        }
    }

    protected R onError(int i) {
        Class a;
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass != null) {
            genericSuperclass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        } else {
            genericSuperclass = null;
        }
        if (genericSuperclass != null) {
            a = com.huawei.hms.support.a.a.a(genericSuperclass);
        } else {
            a = null;
        }
        if (a != null) {
            try {
                this.b = (Result) a.newInstance();
                this.b.setStatus(new Status(i));
            } catch (Exception e) {
                HMSLog.e("PendingResultImpl", "on Error:" + e.getMessage());
                return null;
            }
        }
        return this.b;
    }

    protected boolean checkApiClient(ApiClient apiClient) {
        return true;
    }
}
